<template>
  <div>

    <!-- 热门搜索 -->
	  <van-search v-model="SearchValue" placeholder="请输入搜索关键词" shape="round"/>
    <div class="search_wrap" v-if="resultList.length===0">
    <p class="hot_title">热门搜索</p>
    <ul class="hot_name_wrap">
      <li class="hot_item"  v-for="(obj,index) in hotList" :key="index"
      @click="btn(obj.first)">
    {{obj.first}}</li>
    </ul>
    </div>
<!-- 搜索结果 -->
   <div class="search_wrap" v-else>
     <p class="hot_title">最佳匹配</p>
    <SongItem v-for="obj in resultList" :key="obj.id " :name="obj.name"
 :author="obj.ar[0].name"
 :id="obj.id"
 ></SongItem>
   </div>
  </div>
</template>

<script>
import {hotSearchAPI,SearchkeywordAPI} from '@/api'
import SongItem from '@/components/SongItem'
export default {
data() {
  return {
    SearchValue:' ',
    hotList:[],
    resultList:[],
    //设置一个定时器
    timer:null,
  }
  
},
components:{ SongItem},
methods: {
  async btn(str){
   this.SearchValue=str//将关键字赋给搜索框
    const res=await SearchkeywordAPI({
      type:1,
      keywords:this.SearchValue,
    })
  this.resultList=res.data.result.songs
  setTimeout(() => {
    clearTimeout(this.timer)
  }, );
  }
},
watch:{
   SearchValue(val){ 
    clearTimeout(this.timer) //防止输入框内为空时,还显示请求回来的数据-保证最后那一次网络请求定时器关闭
    if(val.length===0) this.resultList=[];
    this.timer=setTimeout(async() => {
      //搜索框内的值改变时(点击/键盘输入),立即执行
       const res=await SearchkeywordAPI({
      type:1,
      keywords:val,
      
    })
  this.resultList=res.data.result.songs
    }, 500);
   //防抖:n秒内,最后最后执行一次
   //节流:间隔n秒,执行一次
   },
  
},
  async created(){
  const res=await hotSearchAPI()
   this.hotList=res.data.result.hots

  }
}

</script>

<style scoped>
 ::v-deep .van-field__control{
  font-size: 14px !important;
}
.hot_title {
  font-size: 0.32rem;
  color: #666;
}
.search_wrap {
  padding: 0.266667rem;
}
.hot_name_wrap {
  margin: 0.266667rem 0;
}
.hot_item {
  display: inline-block;
  height: 0.853333rem;
  margin-right: 0.213333rem;
  margin-bottom: 0.213333rem;
  padding: 0 0.373333rem;
  font-size: 0.373333rem;
  line-height: 0.853333rem;
  color: #333;
  border-color: #d3d4da;
  border-radius: 0.853333rem;
  border: 1px solid #d3d4da;
}

</style>